#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/bitypes.h>
#include <sys/wait.h>
#include "task.h"
typedef void(*fun_t)();

fun_t tasks[3] = {NULL};

void childrun()
{
  int cnt = 5;
  while(cnt)
  {
    printf("I am child , pid : %d, ppid : %d, cnt : %d\n", getpid(), getppid(), cnt);
    sleep(2);
    cnt--;
  }
}

void LoadTask()
{
  tasks[0] = PrintLog;
  tasks[1] = DownLoad;
  tasks[2] = Mysql;
}

void HandlerTask()
{
  int i = 0;
  for(i = 0; i < 3; i++)
  {
    tasks[i]();
  }
}

void dootherthing()
{
 HandlerTask(); 
}

int main()
{
  printf("I an father, pid : %d, ppid : %d\n", getpid(), getppid());

  pid_t id = fork();
  if(id == 0)
  {
    childrun();
    printf("child quit...\n");
    exit(123);
  }
  LoadTask();
  //father
  while(1){
    int status = 0;
    pid_t rid = waitpid(id, &status, WNOHANG);
    if(rid == 0)
    {
      sleep(1);
      printf("child is runing, father check next time\n");
      dootherthing();
    }
    else if(rid > 0)
    {
      if(WIFEXITED(status))
      {
        printf("child exit code : %d\n", WEXITSTATUS(status));
      }
      else{
        printf("exit unnormal\n");
      }
      break;
    }
    else{
      printf("waitpid failed\n");
    }
  }
  return 0;
}
